package cc.comac.mom.datahandlers.entity;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import cc.comac.mom.dao.entity.QualityAttachmentGroupDao;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.QualityAttachment;
import cc.comac.mom.bean.QualityQarBasicStandardCheck;
import cc.comac.mom.dao.entity.QualityAttachmentDao;
import cc.comac.mom.dao.entity.QualityQarBasicStandardCheckDao;
import cc.comac.mom.entity.QualityAttachmentEntity;
import cc.comac.mom.entity.QualityAttachmentGroupEntity;
import cc.comac.mom.entity.QualityQarBasicStandardCheckEntity;
import cc.comac.mom.redis.IdFactory;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.ResultBean;
@Component
@Transactional
public class QualityQarBasicStandardCheckDataHandler extends ServiceImpl<QualityQarBasicStandardCheckDao, QualityQarBasicStandardCheckEntity>{

	@Autowired
	private QualityQarBasicStandardCheckDao qualityQarBasicStandardCheckDao;
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;
	
	@Resource
	private IdFactory idFactory;

	@Autowired
	private QualityAttachmentDataHandler qualityAttachmentDataHandler;
	
	@Autowired
	private QualityAttachmentGroupDataHandler qualityAttachmentGroupDataHandler;
	@Autowired
	private QualityAttachmentDao qualityAttachmentDao;

	@Autowired
	private QualityAttachmentGroupDao qualityAttachmentGroupDao;
	
	@Value("${upload.tempDir}")
	private String rootPath;
	
	public ResultBean batchInsertQarBasicStandardCheck(List<QualityQarBasicStandardCheck> list) {
		ResultBean resultBean = new ResultBean(true);
		if (list.size() > 0) {
			List<QualityQarBasicStandardCheckEntity> entityList = new ArrayList<QualityQarBasicStandardCheckEntity>();
			List<QualityAttachmentGroupEntity> attachmentGroupIdList = new ArrayList<QualityAttachmentGroupEntity>();
			for (QualityQarBasicStandardCheck qualityQarBasicStandardCheck : list) {
				QualityQarBasicStandardCheckEntity innerData = qualityQarBasicStandardCheck.getInnerData();
				if (innerData.getQarBasicStandardId() == 0) {
					throw new RuntimeException("无法获取qar母本主键!");
				}
				// 当检验表主表有附件信息时创建附件组
				List<Long> attachmentIds = innerData.getAttachmentIds();
				if (attachmentIds != null && attachmentIds.size() > 0) {
					// 生成组id
					long groupId = idFactory.generateId();
					innerData.setGroupId(groupId);
					List<QualityAttachmentEntity> selectBatchIds = qualityAttachmentDao.selectBatchIds(attachmentIds);
					for (QualityAttachmentEntity qualityAttachmentEntity : selectBatchIds) {
						QualityAttachmentGroupEntity qualityAttachmentGroupEntity = new QualityAttachmentGroupEntity();
						qualityAttachmentGroupEntity.setAttachmentId(qualityAttachmentEntity.getId());
						qualityAttachmentGroupEntity.setGroupId(groupId);
						qualityAttachmentGroupEntity.setGroupName(innerData.getCheckItem());
						baseEntityDataUtil.setBaseEntityData(qualityAttachmentGroupEntity);
						// 保存附件组数据，以便批量新增
						attachmentGroupIdList.add(qualityAttachmentGroupEntity);
					}
				}
				// 物理删除附件表数据
				baseEntityDataUtil.setBaseEntityData(innerData);
				entityList.add(innerData);
				// 获取检验的子项集合
				List<QualityQarBasicStandardCheckEntity> qarBasicStandardCheckList = qualityQarBasicStandardCheck.getQarBasicStandardCheckList();
				if (qarBasicStandardCheckList != null && qarBasicStandardCheckList.size() > 0) {
					for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : qarBasicStandardCheckList) {
						// 赋值母本主键
						qualityQarBasicStandardCheckEntity.setQarBasicStandardId(innerData.getQarBasicStandardId());
						baseEntityDataUtil.setBaseEntityData(qualityQarBasicStandardCheckEntity);
						// 赋值父类主键
						qualityQarBasicStandardCheckEntity.setCheckParentId(innerData.getId());
						
						entityList.add(qualityQarBasicStandardCheckEntity);
						
						List<Long> attachmentIds2 = qualityQarBasicStandardCheckEntity.getAttachmentIds();
						if (attachmentIds2 != null && attachmentIds2.size() > 0) {
							long groupId = idFactory.generateId();
							qualityQarBasicStandardCheckEntity.setGroupId(groupId);
							List<QualityAttachmentEntity> selectBatchIds = qualityAttachmentDao.selectBatchIds(attachmentIds2);
							for (QualityAttachmentEntity qualityAttachmentEntity : selectBatchIds) {
								QualityAttachmentGroupEntity qualityAttachmentGroupEntity = new QualityAttachmentGroupEntity();
								qualityAttachmentGroupEntity.setAttachmentId(qualityAttachmentEntity.getId());
								qualityAttachmentGroupEntity.setGroupId(groupId);
								qualityAttachmentGroupEntity.setGroupName(qualityQarBasicStandardCheckEntity.getCheckDetail());
								baseEntityDataUtil.setBaseEntityData(qualityAttachmentGroupEntity);
								// 保存附件组数据，以便批量新增
								attachmentGroupIdList.add(qualityAttachmentGroupEntity);
								// 当附件存在时在检验表中插入对用附件组主键
								qualityQarBasicStandardCheckEntity.setGroupId(groupId);
							}
						}
					}
				}
			}
			// 批量新增检验表中数据
			saveBatch(entityList, entityList.size());
			// 批量新增附件组中的数据
			qualityAttachmentGroupDataHandler.saveBatch(attachmentGroupIdList, attachmentGroupIdList.size());
		}
		return resultBean;
	}

	public List<QualityQarBasicStandardCheck> selectByQarBasicStandardId(long QarBasicStandardId) {
		QueryWrapper<QualityQarBasicStandardCheckEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardCheckEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("qar_basic_standard_id", QarBasicStandardId);
		queryWrapper.eq("check_parent_id", 0);
		List<QualityQarBasicStandardCheckEntity> selectList = qualityQarBasicStandardCheckDao.selectList(queryWrapper);
		List<QualityQarBasicStandardCheck> beanList = new ArrayList<QualityQarBasicStandardCheck>();
		if (selectList.size() > 0) {
			for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : selectList) {
				QualityQarBasicStandardCheck qualityQarBasicStandardCheck = new QualityQarBasicStandardCheck();
				qualityQarBasicStandardCheck.setInnerData(qualityQarBasicStandardCheckEntity);
				// 当附属信息下面有子项数据时
				QueryWrapper<QualityQarBasicStandardCheckEntity> queryWrapper1 = new QueryWrapper<QualityQarBasicStandardCheckEntity>();
				queryWrapper1.eq("row_status", 1);
				queryWrapper1.eq("qar_basic_standard_id", QarBasicStandardId);
				queryWrapper1.eq("check_parent_id", qualityQarBasicStandardCheckEntity.getId());
				List<QualityQarBasicStandardCheckEntity> selectList1 = qualityQarBasicStandardCheckDao.selectList(queryWrapper1);
				if (selectList1.size() > 0) {
					// 当有子项数据
					List<QualityQarBasicStandardCheckEntity> arrayList = new ArrayList<QualityQarBasicStandardCheckEntity>();
					qualityQarBasicStandardCheck.setQarBasicStandardCheckList(arrayList);
					for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity2 : selectList1) {
						arrayList.add(qualityQarBasicStandardCheckEntity2);
					}
				}
				beanList.add(qualityQarBasicStandardCheck);
			}
		}
		return beanList;
	}

	public ResultBean batchDeleteByQarBasicStandardIds(List<Long> ids) {
		ResultBean resultBean = new ResultBean(true);
		// 通过qar母本主键获取对应信息
		QueryWrapper<QualityQarBasicStandardCheckEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardCheckEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.in("qar_basic_standard_id", ids);
		List<QualityQarBasicStandardCheckEntity> selectList = qualityQarBasicStandardCheckDao.selectList(queryWrapper);
		if (selectList.size() > 0) {
			// 软删除对应数据
			for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : selectList) {
				qualityQarBasicStandardCheckEntity.setRowStatus(0);
				baseEntityDataUtil.updateBaseEntityData(qualityQarBasicStandardCheckEntity);
			}
			updateBatchById(selectList, selectList.size());
		}
		return resultBean;
	}

	public ResultBean removeDataByQarBasicStandardUpgradeId(long BasicStandardUpgradeId) {
		ResultBean resultBean = new ResultBean(true);		
		QueryWrapper<QualityQarBasicStandardCheckEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardCheckEntity>();
		queryWrapper.eq("qar_basic_standard_id", BasicStandardUpgradeId);
		List<QualityQarBasicStandardCheckEntity> selectList = qualityQarBasicStandardCheckDao.selectList(queryWrapper);
		if (selectList.size() > 0) {
			ArrayList<Long> groupEntity = new ArrayList<Long>();
			for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : selectList) {
				long groupId = qualityQarBasicStandardCheckEntity.getGroupId();
				if (groupId != 0) {
					QueryWrapper<QualityAttachmentGroupEntity> queryWrapper2 = new QueryWrapper<QualityAttachmentGroupEntity>();
					queryWrapper2.eq("row_status", 1);
					queryWrapper2.eq("group_id", groupId);
					List<QualityAttachmentGroupEntity> selectList2 = qualityAttachmentGroupDao.selectList(queryWrapper2);
					if (selectList2.size() > 0) {
						groupEntity.add(groupId);
					}
				}
			}
			// 删除附件组中的数据通过附件组groupId集合
			qualityAttachmentGroupDataHandler.removeByGroupId(groupEntity);
		}
		// 删除检验数据
		qualityQarBasicStandardCheckDao.delete(queryWrapper);
		return resultBean;
	}
	
	public ResultBean removeDataByQarBasicStandardUpgradeId(List<Long> BasicStandardUpgradeIds) {
		ResultBean resultBean = new ResultBean(true);
		QueryWrapper<QualityQarBasicStandardCheckEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardCheckEntity>();
		queryWrapper.in("qar_basic_standard_id", BasicStandardUpgradeIds);
		List<QualityQarBasicStandardCheckEntity> selectList = qualityQarBasicStandardCheckDao.selectList(queryWrapper);
		if (selectList.size() > 0) {
			for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : selectList) {
				ArrayList<Long> groupEntity = new ArrayList<Long>();
					long groupId = qualityQarBasicStandardCheckEntity.getGroupId();
					if (groupId != 0) {
						QueryWrapper<QualityAttachmentGroupEntity> queryWrapper2 = new QueryWrapper<QualityAttachmentGroupEntity>();
						queryWrapper2.eq("row_status", 1);
						queryWrapper2.eq("group_id", groupId);
						List<QualityAttachmentGroupEntity> selectList2 = qualityAttachmentGroupDao.selectList(queryWrapper2);
						if (selectList2.size() > 0) {
							groupEntity.add(groupId);
						}
					}
				// 物理删除附件组及对应的附件中的数据
				if(groupEntity!=null&&groupEntity.size()>0) {
					qualityAttachmentGroupDataHandler.removeByGroupId(groupEntity);
				}
			}
		}
		qualityQarBasicStandardCheckDao.delete(queryWrapper);
		return resultBean;
	}
	
	// 更新或者新增对应数据
	public ResultBean addOrUpdateData(List<QualityQarBasicStandardCheck> list) {
		ResultBean resultBean = new ResultBean(true);
		if (list.size() > 0) {
			List<QualityQarBasicStandardCheckEntity> entityList = new ArrayList<QualityQarBasicStandardCheckEntity>();
			for (QualityQarBasicStandardCheck qualityQarBasicStandardCheck : list) {
				QualityQarBasicStandardCheckEntity innerData = qualityQarBasicStandardCheck.getInnerData();
				if (innerData.getId() > 0) {
					baseEntityDataUtil.updateBaseEntityData(innerData);
				}else {
					baseEntityDataUtil.setBaseEntityData(innerData);
				}
				entityList.add(innerData);
			}
			saveOrUpdateBatch(entityList,entityList.size());
		}
		return resultBean;
	}
	
	// 上传检验/验证特性
	public ResultBean uploadQarBasicStandardCheck(MultipartFile[] files) {
		ResultBean resultBean = new ResultBean(true);
		List<QualityAttachmentEntity> list = new ArrayList<QualityAttachmentEntity>();
		List<Long> idsList = new ArrayList<Long>();
		for (MultipartFile file : files) {
			// 获取文件全名称
			String originalFilename = file.getOriginalFilename();
			String fileName = file.getName();
			String path = null;
			try {
				// 获取文件路径名
				path = rootPath +"\\"+"upload"+ "\\" + originalFilename;
				// 将文件写入
				File file2 = new File(path);
				if (!file2.getParentFile().exists()) {
					file2.getParentFile().mkdirs();
				}
				file.transferTo(file2);
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
			
			QualityAttachmentEntity qualityAttachmentEntity = new QualityAttachmentEntity();
			qualityAttachmentEntity.setFilePath(path);
			// 获取文件的大小
			DecimalFormat df = new DecimalFormat("0.00");
			String formatMB = df.format((float) file.getSize() / 1048576);
			qualityAttachmentEntity.setFileSize(formatMB+"MB");
			// 获取文件类型后缀
			String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
			qualityAttachmentEntity.setFileType(ext);
			
			qualityAttachmentEntity.setRealName(originalFilename);
			// 定义系统名称
			String uuid = UUID.randomUUID().toString();
			qualityAttachmentEntity.setSysName(uuid);
			baseEntityDataUtil.setBaseEntityData(qualityAttachmentEntity);
			list.add(qualityAttachmentEntity);
			idsList.add(qualityAttachmentEntity.getId());
		}
		qualityAttachmentDataHandler.saveBatch(list, list.size());
		resultBean.setObject(idsList);
		return resultBean;
	}
	
	// 查询并排列成集合
	public List<QualityQarBasicStandardCheck> selectCheckMainByBasicStandardCheckId (long basicStandardCheckId) {
		List<QualityQarBasicStandardCheck> checkList = new ArrayList<QualityQarBasicStandardCheck>();
		QueryWrapper<QualityQarBasicStandardCheckEntity> queryWrapper = new QueryWrapper<QualityQarBasicStandardCheckEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("qar_basic_standard_id", basicStandardCheckId);
		List<QualityQarBasicStandardCheckEntity> selectList = qualityQarBasicStandardCheckDao.selectList(queryWrapper);
		// 筛选父类
		List<QualityQarBasicStandardCheckEntity> parentList = selectList.stream().filter(item -> item.getCheckParentId() == 0).collect(Collectors.toList());
		// 筛选子类
		List<QualityQarBasicStandardCheckEntity> childList = selectList.stream().filter(item -> item.getCheckParentId() != 0).collect(Collectors.toList());
		// 遍历父类数据
		for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity : parentList) {
			QualityQarBasicStandardCheck check = new QualityQarBasicStandardCheck();
			check.setInnerData(qualityQarBasicStandardCheckEntity);
			List<QualityQarBasicStandardCheckEntity> entityList = new ArrayList<QualityQarBasicStandardCheckEntity>();
			check.setQarBasicStandardCheckList(entityList);
			// 添加对象集合
			checkList.add(check);
			for (QualityQarBasicStandardCheckEntity qualityQarBasicStandardCheckEntity2 : childList) {
				// 当是当前对象子类时
				if (qualityQarBasicStandardCheckEntity2.getCheckParentId() == qualityQarBasicStandardCheckEntity.getId()) {
					entityList.add(qualityQarBasicStandardCheckEntity2);
				}
			}
		}
		return checkList;
	}

}
